package com.service.oos;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

import javax.servlet.http.HttpServletResponse;

import com.common.DateUtils;
import com.common.spring.SpringMvcUtils;
import com.dao.oos.CorrectiveSuperviseDao;
import com.dao.oos.OosDataDao;
import com.dao.sys.SysDeptMapper;
import com.model.oos.*;
import com.model.sys.SysDept;
import com.model.sys.SysUser;
import com.service.sys.WXService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.excel.EasyExcel;
import com.common.StringUtils;
import com.common.easyui.EasyuiUtils;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.dao.oos.CorrectiveActionDao;
import com.common.model.Global;
import org.springframework.util.CollectionUtils;

@Service
public class CorrectiveActionService {
	static final Logger logger = LoggerFactory.getLogger(CorrectiveActionService.class);

	@Autowired
	CorrectiveActionDao correctiveActionDao;
	@Autowired
	OosDataDao oosDataDao;
	@Autowired
	CorrectiveSuperviseDao correctiveSuperviseDao;
	@Autowired
	SysDeptMapper sysDeptMapper;
	@Autowired
	CorrectiveSuperviseHistoryService correctiveSuperviseHistoryService;
	@Autowired
	WXService wxService;

	/**
	 * 列表查询
	 *
	 * @param queryMap
	 * @return
	 */
	public HttpResult selectList(Map<String, Object> queryMap) {
		HttpResult httpResult = new HttpResult();
		EasyuiUtils.addPageNum(queryMap);
		EasyuiUtils.addFilter(queryMap);
		List<CorrectiveActionModel> list = correctiveActionDao.selectList(queryMap);
		int count = correctiveActionDao.selectListCount(queryMap);
		httpResult.setRows(list);
		httpResult.setTotal(count);
		logger.info("selectList:{}", list);
		return httpResult;
	}

	/**
	 * 详情
	 *
	 * @param
	 * @return
	 */
	public HttpResult selectInfor(String corId) {
		HttpResult httpResult = new HttpResult();
		CorrectiveActionModel correctiveActionModel = correctiveActionDao.load(corId);
		if (null != correctiveActionModel) {
			Map params = new HashMap();
			params.put("corId", corId);
			// 获取所有行动项
			List<CorrectiveSuperviseModel> supervise = correctiveSuperviseDao.selectListByCorId(params);
			correctiveActionModel.setSupervises(supervise);
		}
		httpResult.setData(correctiveActionModel);
		httpResult.setCode(HttpStatus.SUCCESS_CODE);
		return httpResult;
	}

	/**
	 * 保存
	 *
	 * @param
	 * @return
	 */
	public HttpResult save(CorrectiveActionModel correctiveActionModel) {
		if (correctiveActionModel == null) {
			return HttpResult.error("参数不能为空");
		}
		HttpResult httpResult = new HttpResult();
		String corId = correctiveActionModel.getCorId();
		int result = 0;
		if (!StringUtils.isNotNull(corId)) {
			corId = UUID.randomUUID().toString();
			correctiveActionModel.setCorId(corId);
			correctiveActionModel.setCorNum(createCorrCode());
			result = correctiveActionDao.insert(correctiveActionModel);
		} else {
			result = correctiveActionDao.update(correctiveActionModel);
		}
		if (result > 0) {
			// 保存行动项
			int supResult = 0;
			List<CorrectiveSuperviseModel> supervises = correctiveActionModel.getSupervises();
			if (!CollectionUtils.isEmpty(supervises)) {
				for (CorrectiveSuperviseModel correctiveSuperviseModel : supervises) {
					String supId = correctiveSuperviseModel.getSupId();
					String deptId = correctiveSuperviseModel.getDutyDeptCode();
					// 根据deptId,获取该部门责任人
					Map<String, String> excutorInfor = oosDataDao.selectDeptByPrimaryKey(deptId);
					if (CollectionUtils.isEmpty(excutorInfor)) {
						return HttpResult.error("未查询到部门负责人信息，请联系管理员。");
					}
					// 若已存在，则更新
					if (StringUtils.isNotNull(supId)) {
						// 根据sId查询该条数据是否已经被责任部门维护过
						CorrectiveSuperviseModel oldCorrectiveSupervise = correctiveSuperviseDao.load(supId);
						if (null != oldCorrectiveSupervise) {
							// 前端传回的部门id与当前已存在的数据部门id不符合，表示已将该条数据的责任部门更换掉了
							if (!oldCorrectiveSupervise.getDutyDeptCode()
									.equals(correctiveSuperviseModel.getDutyDeptCode())) {
								// 将原措施更新为已删除
								oldCorrectiveSupervise.setDelFlag("1");
								correctiveSuperviseDao.update(oldCorrectiveSupervise);
								// 新增一条新部门的行动项
								correctiveSuperviseModel.setSupId(UUID.randomUUID().toString());
								// 责任人账号
								correctiveSuperviseModel.setDutyPersonCode(excutorInfor.get("deptLeader"));
								// 责任人姓名
								correctiveSuperviseModel.setDutyPersonName(excutorInfor.get("userName"));
								// correctiveSuperviseModel.setDutyPersonId(excutorInfor.get(""));
								// 措施
								correctiveSuperviseModel.setAction("");
								// 实际完成时间
								correctiveSuperviseModel.setRealCompleteDate(null);
								// 计划完成时间
								correctiveSuperviseModel.setPlanCompleteDate(null);
								// 原因
								correctiveSuperviseModel.setCause("");
								// 整改效果
								correctiveSuperviseModel.setReformStatus("");
								correctiveSuperviseModel.setStatus(correctiveActionModel.getStatus());
								supResult += correctiveSuperviseDao.insert(correctiveSuperviseModel);
								// 如果status是提交，则不发送消息
								if (correctiveSuperviseModel.getStatus().equals(Global.NO + "")) {
									// wxUtil.sendTxtMessage(excutorInfor.get("deptLeader"), "【OOS提醒消息】：编号：" +
									// osCode + "有您的一条待处理行动项，请在一小时内登录CMP处理。");
								}
							} else {
								// 若点击提交，则将各措施状态改为'1'
								if (correctiveActionModel.getStatus().equals(Global.YES + "")) {
									correctiveSuperviseModel.setStatus("1");
								}
								supResult += correctiveSuperviseDao.update(correctiveSuperviseModel);
							}
						}
					} else {
						// 关联问题id
						correctiveSuperviseModel.setCorId(corId);
						// 设置行动项id
						correctiveSuperviseModel.setSupId(UUID.randomUUID().toString());
						// 责任人账号
						correctiveSuperviseModel.setDutyPersonCode(excutorInfor.get("deptLeader"));
						// 责任人姓名
						correctiveSuperviseModel.setDutyPersonName(excutorInfor.get("userName"));
						correctiveSuperviseModel.setStatus(correctiveActionModel.getStatus());
						supResult += correctiveSuperviseDao.insert(correctiveSuperviseModel);
						if (correctiveSuperviseModel.getStatus().equals(Global.NO + "")) {
							// wxUtil.sendTxtMessage(excutorInfor.get("deptLeader"), "【OOS提醒消息】：编号：" +
							// osCode + "有您的一条待处理行动项，请在一小时内登录CMP处理。");
						}
					}
				}
				if (supResult != supervises.size()) {
					return HttpResult.error("保存失败");
				}
			}
			// 如果是完成，则将该下的行动项改为1
			if (correctiveActionModel.getStatus().equals(Global.YES + "")) {
				correctiveSuperviseDao.updateCompleteByCorId(corId);
			}
		} else {
			return HttpResult.error("保存失败");
		}
		return HttpResult.ok("保存成功", this.selectInfor(corId).getData());
	}

	/*
	 * 更新 此功能提供给各责任部门，修改行动项
	 * 
	 * @param
	 * 
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public HttpResult updateForDutyDept(CorrectiveActionModel correctiveActionModel) throws IOException {
		if (null == correctiveActionModel) {
			return HttpResult.error("数据为空");
		}
		if (StringUtils.isNullOrEmpty(correctiveActionModel.getCorId())) {
			return HttpResult.error("纠正问题主键为空");
		}
		CorrectiveActionModel actionTmp = correctiveActionDao.load(correctiveActionModel.getCorId());
		if (null == actionTmp || (Global.YES + "").equals(actionTmp)) {
			return HttpResult.error("该督办任务已完成或不存在，无需操作。");
		}
		String actionStatus = correctiveActionModel.getStatus();
		// 保存整改措施
		List<CorrectiveSuperviseModel> supervies = correctiveActionModel.getSupervises();
		int result = 0;
		if (!CollectionUtils.isEmpty(supervies)) {
			for (CorrectiveSuperviseModel correctiveSupervise : supervies) {
				if (actionStatus.equals(Global.YES + "")) {
					correctiveSupervise.setRealCompleteDate(DateUtils.getCurrentTime());
				} else {
					correctiveSupervise.setRealCompleteDate(null);
				}
				correctiveSupervise.setStatus(actionStatus);
				result += correctiveSuperviseDao.update(correctiveSupervise);
				// 记录修改历史
				CorrectiveSuperviseHistoryModel correctiveSuperviseHistoryModel = new CorrectiveSuperviseHistoryModel();
				BeanUtils.copyProperties(correctiveSupervise, correctiveSuperviseHistoryModel);
				correctiveSuperviseHistoryService.save(correctiveSuperviseHistoryModel);

			}
			if (result != supervies.size()) {
				return HttpResult.error("保存失败");
			}
		}
		return HttpResult.ok("保存成功", correctiveActionModel);
	}

	/**
	 * 提交
	 *
	 * @param
	 * @return
	 */
	public HttpResult commit(CorrectiveActionModel correctiveActionModel) {
		if (correctiveActionModel == null) {
			return HttpResult.error("参数不能为空");
		}
		correctiveActionModel.setStatus(Global.YES + "");
		HttpResult httpResult = new HttpResult();
		int result = 0;
		result = correctiveActionDao.update(correctiveActionModel);
		if (result > 0) {
			httpResult.setMsg(correctiveActionModel.getStatus().equals(Global.YES + "") ? "提交成功!" : "保存成功!");
			httpResult.setData(correctiveActionModel);
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg(correctiveActionModel.getStatus().equals(Global.YES + "") ? "提交失败!" : "保存失败!");
		}
		return httpResult;
	}

	/**
	 * 删除
	 *
	 * @param
	 * @return
	 */
	public HttpResult delete(String corId) {
		if (!StringUtils.isNotNull(corId)) {
			return HttpResult.error("参数不能为空");
		}
		CorrectiveActionModel model = correctiveActionDao.load(corId);
		if (!model.getStatus().equals(Global.NO + "")) {
			return HttpResult.error("已提交状态，不可删除！");
		}
		HttpResult httpResult = new HttpResult();
		int result = correctiveActionDao.delAction(corId);
		// 删除该项下的行动项
		correctiveSuperviseDao.delByCorId(corId);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 撤回
	 *
	 * @param
	 * @return
	 */
	public HttpResult back(String corId) {
		if (!StringUtils.isNotNull(corId)) {
			return HttpResult.error("参数不能为空");
		}
		CorrectiveActionModel model = correctiveActionDao.load(corId);



		HttpResult httpResult = new HttpResult();
		model.setStatus(Global.NO + "");
		int result = correctiveActionDao.update(model);
		if (result > 0) {
			httpResult.setMsg("删除成功！");
		} else {
			httpResult.setCode(HttpStatus.GLOBAL_EXCEPTION_CODE);
			httpResult.setMsg("不存在此条数据！");
		}
		return httpResult;
	}

	/**
	 * 导出
	 *
	 * @param queryMap
	 * @param response
	 */
	public void export(Map<String, Object> queryMap, HttpServletResponse response) {
		List<CorrectiveActionModel> list = correctiveActionDao.selectList(queryMap);
		logger.info("export:{}", list);
		try {
			EasyExcel.write(response.getOutputStream(), CorrectiveActionModel.class).sheet("模板").doWrite(list);
		} catch (IOException e) {
			logger.error("导出错误:{}", e.getMessage());
		}

	}

	public String createCorrCode() {
		String year = DateUtils.getCurrentYear();
		String month = DateUtils.getCurrentMonth();
		String queryparsm = year + "-" + month;
		int count = correctiveActionDao.queryCurrentOOSCount(queryparsm);
		AtomicInteger atomicInteger = new AtomicInteger(000);
		atomicInteger.addAndGet(count);
		int num = atomicInteger.incrementAndGet();
		// 补0
		DecimalFormat decimalFormat = new DecimalFormat("000");
		String serNum = decimalFormat.format(num);
		return year + month + serNum;
	}
}
